<script lang="jsx" setup>
import dayjs from 'dayjs';
import { computed, ref } from 'vue';
import { UUID } from 'uuidjs';
import { AppstoreOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import { useElementSize } from '@vueuse/core';
import { Empty } from 'ant-design-vue';
import { getAoiInfo } from '@/service/api/modules/trace/one-code-trace';
import { getExceptionImg, getExceptionImgList } from '@/service/api/modules/trace/aoi';

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

const isGetOk = ref(false);
const props = defineProps({
  type: {
    type: String,
    default: ''
  }
});

const prodNo = defineModel('prodNo', { type: String, default: '' });
const tableRef = ref(null);
const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'panelId',
    dataIndex: 'panelId',
    title: 'PNL编号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 200
  },
  {
    key: 'upTime',
    dataIndex: 'upTime',
    title: '时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180,
    customRender: ({ record }) => {
      return dayjs(record.upTime).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'positiveprodNo',
    dataIndex: 'positiveprodNo',
    title: '正面型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 165
  },
  {
    key: 'negativeprodNo',
    dataIndex: 'negativeprodNo',
    title: '反面型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 165
  }
];

const page = ref({
  pageNum: 1,
  pageSize: 200,
  total: 0
});

const loading = ref(false);
const tableData = ref([]);

function getTableData() {
  if (!prodNo.value) return;
  loading.value = true;
  getAoiInfo({
    prodNo: prodNo.value,
    deviceNo: props.type,
    ...page.value
  })
    .then(({ data, error }) => {
      if (!error) {
        data.list.forEach((item, index) => {
          item.dataIndex = index + 1;
          item.tableUuid = UUID.genV4().hexNoDelim;
        });
        tableData.value = data.list;
        // leftTableDataLoadSucess(data.list);
        tableRef.value.setPagination(data.total);
        isGetOk.value = true;
        if (data.list.length) {
          leftTableDataLoadSucess(data.list);
        }
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function handlePageChange(pageNum, pageSize) {
  page.value.pageNum = pageNum;
  page.value.pageSize = pageSize;
  getTableData();
}

const activeKey = ref('1');

// 异常项
const defectTableColumn = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'defectsKind',
    dataIndex: 'defectsKind',
    title: '异常名称',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'defectsNum',
    dataIndex: 'defectsNum',
    title: '异常次数',
    align: 'center',
    checked: true,
    ellipsis: true,
    sorter: {
      compare: (a, b) => a.defectsNum - b.defectsNum,
      multiple: 2
    }
  }
];
const baseUrl = ref('');
// 获取基础url
function getBaseUrl() {
  if (location.hostname === 'localhost') {
    baseUrl.value = 'http://192.168.166.166/dev-api/';
    return;
  }
  baseUrl.value = '/dev-api/';
}
getBaseUrl();

// 分页相关
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(200);
const pageSizeOptions = ref(['50', '100', '200', '500', '1000', '2000']);
const positiveSideData = ref([]);
const positiveSideAbnormalCount = computed(() => {
  return positiveSideData.value.reduce((acc, cur) => acc + cur.defectsNum, 0);
}); // 正面异常总次数
const reverseSideData = ref([]);
const reverseSideAbnormalCount = computed(() => {
  return reverseSideData.value.reduce((acc, cur) => acc + cur.defectsNum, 0);
}); // 反面异常总次数
const showType = ref('list');
const imgList = ref([]);
const viewImgList = ref([]);
const imgContentRef = ref(null);
const currentLeftRow = ref(null);
function getImgList() {
  getExceptionImgList({
    path: `${currentLeftRow.value.path.replace('D:', '').replace(`\\`, '').replace(/\\/g, '/')}/`,
    type: props.type
  }).then(({ data, error }) => {
    if (!error) {
      console.log('图片信息：', data);

      imgList.value = data
        .filter(item => {
          const type = item.split('.')[1];
          return type === 'jpeg' || type === 'png' || type === 'gif' || type === 'jpg';
        })

        .map(item => {
          return {
            fileName: item,
            url: `${baseUrl.value}qms/oneCodeFileReader/${props.type}?filename=${currentLeftRow.value.path.replace('D:', '').replace(`\\`, '').replace(/\\/g, '/')}/${item}`,
            size: null,
            time: dayjs(currentLeftRow.value.upTime).format('YYYY-MM-DD HH:mm:ss')
          };
        });
      imgList.value.forEach((item, index) => {
        item.dataIndex = index + 1;
        item.tableUuid = UUID.genV4().hexNoDelim;
      });
      total.value = imgList.value.length;
      pageSizeOptions.value.push(data.length.toString());
      viewImgList.value = imgList.value.map(item => item.url);
    }
  });
}
function handleTableRowClick(row) {
  currentLeftRow.value = row;
  getExceptionImg({ id: row.id }).then(({ data, error }) => {
    if (!error) {
      const positiveSide = data.filter(item => Number(item.pn) === 0);
      const reverseSide = data.filter(item => Number(item.pn) === 1);
      positiveSide.forEach((item, index) => {
        item.dataIndex = index + 1;
      });
      reverseSide.forEach((item, index) => {
        item.dataIndex = index + 1;
      });
      positiveSideAbnormalCount.value = positiveSide.reduce((acc, cur) => acc + cur.defectsNum, 0);
      reverseSideAbnormalCount.value = reverseSide.reduce((acc, cur) => acc + cur.defectsNum, 0);
      positiveSideData.value = positiveSide;
      reverseSideData.value = reverseSide;
    }
  });
  getImgList();
}

let isFirst = 0;
function leftTableDataLoadSucess(data) {
  if (isFirst === 2) return;
  isFirst += 1;
  tableRef.value.setCurrentRowId(data[0]);
  currentLeftRow.value = data[0];
  // getImgList();
  handleTableRowClick(data[0]);
}

function typeChange() {
  pageNum.value = 1;
}
const imgTableColumns = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'fileName',
    dataIndex: 'fileName',
    title: '文件名称',
    align: 'center',
    checked: true,
    ellipsis: true,
    fixed: 'left',
    width: 150
  },
  {
    key: 'time',
    dataIndex: 'time',
    title: '上传时间',
    align: 'center',
    fixed: 'left',
    checked: true,
    ellipsis: true,
    width: 180
  },
  {
    key: 'url',
    dataIndex: 'url',
    title: '图片',
    align: 'center',
    checked: true,
    fixed: 'left',
    ellipsis: true,
    width: 100,
    customRender: ({ record }) => {
      return (
        <div class="w-full flex-center cursor-pointer" onClick={() => handleViewImg(record.dataIndex - 1)}>
          <img width={22} src={record.url} alt="" key={record.url} />
        </div>
      );
    }
  }
];

// 预览图片
const viewImgVisible = ref(false);
const currentImgViewIndex = ref(0);
const modalImgRef = ref(null);
const imgScale = ref(1);
const rotate = ref(0);
function handleViewImg(index) {
  viewImgVisible.value = true;
  currentImgViewIndex.value = index;
}

const computedList = computed(() => {
  // 计算起始索引
  const startIndex = (pageNum.value - 1) * pageSize.value;
  // 计算结束索引
  const endIndex = startIndex + pageSize.value;

  // 截取出当前页的数据
  const paginatedData = imgList.value.slice(startIndex, endIndex);
  console.log('paginatedData', paginatedData);

  return paginatedData;
});

const { height } = useElementSize(imgContentRef);

const tableScrollY = computed(() => {
  return height.value - 40;
});

function onChange(page, pageSizes) {
  pageNum.value = page;
  pageSize.value = pageSizes;
  imgContentRef.value.scrollTop = 0;
}

function handleNext() {
  if (currentImgViewIndex.value === imgList.value.length - 1) return;
  resetStyle();
  currentImgViewIndex.value += 1;
}

function handleImgPreviou() {
  if (currentImgViewIndex.value === 0) return;
  resetStyle();
  currentImgViewIndex.value -= 1;
}

function resetStyle() {
  imgScale.value = 1;
  rotate.value = 0;
}

function handleScale(type) {
  if (type === 'plus') {
    imgScale.value += 0.1;
  } else {
    imgScale.value -= 0.1;
  }
}

function handleScroll(event) {
  event.stopPropagation();

  if (event.deltaY < 0) {
    // 向上滚动放大
    imgScale.value += 0.1;
  } else {
    // 向下滚动缩小
    imgScale.value -= 0.1;
  }
}

function handleRotate(type) {
  if (type === 'left') {
    rotate.value -= 90;
  } else {
    rotate.value += 90;
  }
}

function handleViewImgClose() {
  viewImgVisible.value = false;
  resetStyle();
}

function reset() {
  isGetOk.value = false;
  tableRef.value?.reset();
  tableData.value = [];
  page.value = {
    pageNum: 1,
    pageSize: 200,
    total: 0
  };
  imgList.value = [];
  positiveSideData.value = [];
  reverseSideData.value = [];
}

defineExpose({
  getTableData,
  reset
});
</script>

<template>
  <div class="avi-warp h-full w-full">
    <ARow class="avi-warp-row h-full" :gutter="15">
      <ACol :span="7" class="h-full">
        <Table
          ref="tableRef"
          :column="column"
          :show-row-selection="false"
          :data-source="tableData"
          row-key="tableUuid"
          :scroll="{ y: 'auto' }"
          :is-init-get-data="false"
          class="h-full"
          :loading="loading"
          :show-card-header="false"
          :show-quick-jumper="false"
          @pagination-change="handlePageChange"
          @table-row-click="handleTableRowClick"
        ></Table>
      </ACol>
      <ACol :span="17" class="h-full">
        <div class="right-warp h-full flex">
          <div class="defect-list h-full w-300px">
            <ATabs v-model:activeKey="activeKey" size="small" type="card">
              <ATabPane key="1" tab="正面异常明细" class="pt-10px">
                <STable
                  :columns="defectTableColumn"
                  :pagination="false"
                  :data-source="positiveSideData"
                  size="small"
                  row-key="id"
                  :row-height="23"
                  class="no-has-pagination-table has-footer-table h-full"
                  bordered
                  summary-fixed
                >
                  <template #summary>
                    <STableSummaryRow>
                      <STableSummaryCell :index="0" :col-span="2" class="text-center color-blue-600 font-bold">
                        总异常次数
                      </STableSummaryCell>

                      <STableSummaryCell :index="1" class="text-center color-blue-600 font-bold">
                        {{ positiveSideAbnormalCount }}
                      </STableSummaryCell>
                    </STableSummaryRow>
                  </template>
                </STable>
              </ATabPane>

              <ATabPane key="2" tab="反面异常明细" class="pt-10px">
                <STable
                  :columns="defectTableColumn"
                  :pagination="false"
                  :data-source="reverseSideData"
                  size="small"
                  row-key="id"
                  class="no-has-pagination-table has-footer-table h-full"
                  :row-height="23"
                  bordered
                  summary-fixed
                >
                  <template #summary>
                    <STableSummaryRow>
                      <STableSummaryCell :index="0" :col-span="2" class="text-center color-blue-600 font-bold">
                        总异常次数
                      </STableSummaryCell>

                      <STableSummaryCell :index="1" class="text-center color-blue-600 font-bold">
                        {{ reverseSideAbnormalCount }}
                      </STableSummaryCell>
                    </STableSummaryRow>
                  </template>
                </STable>
              </ATabPane>
            </ATabs>
          </div>
          <div class="img-list-warp">
            <div class="change-type">
              <div class="show-type center flex">
                <div class="lable mr-5px line-height-36px">
                  <span>显示形式:</span>
                </div>
                <ARadioGroup v-model:value="showType" size="medium" @change="typeChange">
                  <ARadioButton value="table">
                    <UnorderedListOutlined />
                  </ARadioButton>
                  <ARadioButton value="list">
                    <AppstoreOutlined />
                  </ARadioButton>
                </ARadioGroup>
              </div>
            </div>
            <div ref="imgContentRef" class="img-content w-full">
              <template v-if="showType === 'list'">
                <template v-if="computedList.length">
                  <div class="img-list h-full w-full overflow-auto">
                    <template v-for="(item, index) in computedList" :key="item.url">
                      <div class="img-item" @click="handleViewImg(index)">
                        <ATooltip placement="right">
                          <img v-lazy="item.url" alt="" />
                          <template #title>
                            <div class="img-data">
                              <div class="data-item flex">
                                <div class="label">文件名称:</div>
                                <div class="value">{{ item.fileName }}</div>
                              </div>
                              <div class="data-item flex">
                                <div class="label">上传时间:</div>
                                <div class="value">{{ item.time }}</div>
                              </div>
                            </div>
                          </template>
                        </ATooltip>
                        <div class="img-desc">{{ item.fileName }}</div>
                      </div>
                    </template>
                  </div>
                </template>
                <template v-else>
                  <div class="h-full w-full flex flex-center">
                    <AEmpty :image="simpleImage" />
                  </div>
                </template>
              </template>

              <!-- <div  class="h-full w-full table"> -->
              <STable
                v-if="showType === 'table'"
                :data-source="computedList"
                :columns="imgTableColumns"
                size="small"
                :pagination="false"
                row-key="tableUuid"
                :show-row-selection="false"
                :scroll="{ y: tableScrollY }"
                class="no-has-pagination-table img-table h-full w-full"
                bordered
              ></STable>
              <!-- </div> -->
            </div>
            <div class="pagination mt-8px flex justify-end">
              <APagination
                v-model:current="pageNum"
                v-model:page-size="pageSize"
                show-size-changer
                show-quick-jumper
                :total="total"
                :page-size-options="pageSizeOptions"
                size="small"
                :show-header="false"
                @change="onChange"
              />
            </div>
          </div>
        </div>
      </ACol>
    </ARow>

    <Modal
      v-model:visible="viewImgVisible"
      :title="computedList?.[currentImgViewIndex]?.fileName"
      width="750px"
      height="650px"
      @close="handleViewImgClose"
    >
      <div class="view-img-content" @wheel="handleScroll">
        <img
          ref="modalImgRef"
          :style="{ transform: ` translate(-50%, -50%) scale(${imgScale}) rotate(${rotate}deg)` }"
          :src="viewImgList[currentImgViewIndex]"
          alt=""
        />
      </div>
      <template #footer>
        <div class="modal-footer">
          <AButton @click="handleRotate('left')">左旋转</AButton>
          <AButton @click="handleRotate('right')">右旋转</AButton>
          <AButton @click="handleScale('plus')">放大</AButton>
          <AButton @click="handleScale('minus')">缩小</AButton>
          <AButton @click="handleImgPreviou">上一张</AButton>
          <AButton @click="handleNext">下一张</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.avi-warp-row {
  :deep(.surely-table-wrapper) {
    .ant-spin-nested-loading {
      .surely-table-column-title {
        color: #646cff;
        font-weight: bold;
      }
    }
  }
  margin-right: 0 !important;
  .defect-list {
    :deep(.ant-tabs) {
      height: 100%;
      .ant-tabs-content {
        height: 100%;
      }
    }
  }
  .img-list-warp {
    width: calc(100% - 300px);

    .change-type {
      display: flex;
      justify-content: flex-end;
      height: 36px;
      margin-bottom: 10px;
    }

    // :deep(.ant-table-wrapper) {
    //   .ant-table {
    //     height: 100% !important;
    //   }
    // }

    .img-content {
      padding-left: 8px;
      height: calc(100% - 82px);
      .img-list {
        padding: 15px;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        .img-item {
          width: 80px;
          height: 100px;
          padding: 10px;
          box-sizing: border-box;

          &:hover {
            background: #f0f9f7 !important;
            cursor: pointer;
            // border: 1px solid #ddefeb;
          }

          .img-desc {
            white-space: nowrap;
            /* 强制文本在一行内显示 */
            overflow: hidden;
            /* 隐藏溢出的内容 */
            text-overflow: ellipsis;
            /* 显示省略号 */
            text-align: center;
          }
        }
      }
      .table {
        :deep(.ant-card) {
          .ant-card-body {
            padding-bottom: 0;
          }
        }
      }
    }
  }
}

.view-img-content {
  width: 100%;
  height: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  position: relative;
  overflow: hidden;
  img {
    position: absolute;
    top: 50%;
    left: 50%;
    transition: all 200ms;
    transform: translate(-50%, -50%);
  }
}
</style>
